<?php

namespace app\admin\controller\vppz;

use app\common\controller\Backend;
//use think\addons\Service;
//use think\Exception;

use app\admin\model\vppz\App;


/**
 * 系统配置
 *
 * @icon fa fa-gears
 */
class PhysicalItemRel extends Base
{
	protected $branch = 0;	// 0：插件市场版，1：自主授权版

    protected $model = null;

   protected $searchFields = ['id','name'];

    public function _initialize()
    {
        parent::_initialize();
        $ids = input('ids');
        $this->assignconfig('package_id',$ids);
        $this->assign('package_id',$ids);
        $this->model = new \app\admin\model\vppz\PhysicalPackageItemRel;
        $this->examModel = new \app\admin\model\vppz\PhysicalExam;
        $this->packageModel = new \app\admin\model\vppz\PhysicalExamPackage;
    }
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $ids = input('ids');

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->with(['physical_exam'])
                    ->where(['package_id'=>$ids])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('physical_exam')->visible(['name','price']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $package_id = input('ids');
        if ($this->request->isPost()) {
            $this->modelValidate = true;
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $form = $this->preExcludeFields($params);
            $result = false;
            try {
                $Note = $this->model->where(['item_id'=>$form['item_id'],'package_id'=>$package_id])->find();
                if(empty($Note) === FALSE){
					$this->error('项目已存在，重试看看呢');
                }
                $packageItem = $this->examModel->find($form['item_id']);
                if($packageItem->price <= $form['item_discount']){
                    $this->error('优惠价格高于项目原价，请调整后提交');
                }
                $package_cate = $this->packageModel->where([
                    'id'=>$package_id
                ])->value('cate_id');
                if($package_cate == 'bijian'){
                    if($form['item_type'] != 1){
                        $this->error('当前套餐是必检套餐，无法添加自选项');
                    }
                }else if($package_cate == 'auto'){
                    if($form['item_type'] == 1){
                        $this->error('当前套餐是自选套餐，无法添加必检项');
                    }
                }
                $Data = array(
                    'item_id'=>$form['item_id'],
                    'package_id'=>$package_id,
                    'item_type'=>$form['item_type'],
                    'item_discount'=>$form['item_discount']
                );
                $ret = $this->model->save($Data);
                $this->updatePackage($package_id);
                if(!$ret){
					$this->error('服务器刚刚走神了，重试看看呢');
				}
                $this->success();
            } catch (ValidateException|PDOException|Exception $e) {
                $this->error($e->getMessage());
            }
        }
        $item_types = array(
            array(
                'id'=>1,
                'name'=>'必选'
            ),
            array(
                'id'=>2,
                'name'=>'默认选中'
            ),
            array(
                'id'=>3,
                'name'=>'默认不选'
            )
        );
        $this->view->assign('item_types',$item_types);
        return parent::add();
    }
    private function updatePackage($package_id){
        $price = 0;
        $total_original_price = 0;
        $total_discount = 0;
        $data = $this->model->where([
            'package_id'=>$package_id
        ])->select();
        if(empty($data) === FALSE){
            foreach ($data as &$dv){
                $itemPrice = $this->examModel->where([
                    'id'=>$dv['item_id']
                ])->value('price');
                $price += $itemPrice;
                $price-=$dv['item_discount'];
                $total_original_price+=$itemPrice;
                $total_discount+=$dv['item_discount'];
            }
        }
        $this->packageModel->where([
            'id'=>$package_id
        ])->update(
            array(
                'final_price'=>$price,
                'total_original_price'=>$total_original_price,
                'total_discount'=>$total_discount,
            )
        );
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $item_types = array(
            array(
                'id'=>1,
                'name'=>'必选'
            ),
            array(
                'id'=>2,
                'name'=>'默认选中'
            ),
            array(
                'id'=>3,
                'name'=>'默认不选'
            )
        );
        if(empty($item_types) === FALSE){
            foreach ($item_types as &$v){
                if($v['id'] == $row['item_type']){
                    $v['selected'] = 1;
                }else{
                    $v['selected'] = 0;
                }
            }
        }
        $this->view->assign('item_types',$item_types);
        if (false === $this->request->isPost()) {
            $packageItem = $this->examModel->find($row['item_id']);
            $row['item_price_info'] = $packageItem->name.'--￥'.$packageItem->price;
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $form = $this->preExcludeFields($params);
        $result = false;
        try {
            $packageItem = $this->examModel->find($form['item_id']);
                if($packageItem->price <= $form['item_discount']){
                    $this->error('优惠价格高于项目原价，请调整后提交');
                }
                $package_cate = $this->packageModel->where([
                    'id'=>$row['package_id']
                ])->value('cate_id');
                if($package_cate == 'bijian'){
                    if($form['item_type'] != 1){
                        $this->error('当前套餐是必检套餐，无法添加自选项');
                    }
                }else if($package_cate == 'auto'){
                    if($form['item_type'] == 1){
                        $this->error('当前套餐是自选套餐，无法添加必检项');
                    }
                }
            $Data = array(
                'item_id'=>$row['item_id'],
                'package_id'=>$row['package_id'],
                'item_type'=>$form['item_type'],
                'updatetime'=>time(),
                'item_discount'=>$form['item_discount']
            );
            $ret = $this->model->where(['id'=>$ids])->update($Data);

            $this->updatePackage($row['package_id']);
            if(!$ret){
                $this->error('服务器刚刚走神了，重试看看呢');
            }
            $this->success();
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();

    }
public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $row = $this->model->get($ids);
            $this->model->destroy($ids);
            $this->updatePackage($row['package_id']);
            $this->success();
        }
        $this->error();
    }
}
